// Learn cc.Class:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/class/index.html
// Learn Attribute:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/reference/attributes/index.html
// Learn life-cycle callbacks:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/life-cycle-callbacks/index.html

/**
 * 聊天室
 * 彩种投注房间主界面
 */
cc.Class({
    extends: cc.Component,

    properties: {        
        //聊天室名字
        labChatName:cc.Label,

        //用户余额
        labGold: cc.Label,

        //根目录
        content:cc.Node,
  
        //聊天信息
        swChat:cc.ScrollView,
 
        //投注面板
        betContent:cc.Node,

        //输入框
        edMsg:cc.EditBox,

        //输入信息条
        fbItemIn:cc.Prefab,
 
        //输出信息条
        fbItemOut:cc.Prefab,

        //输入投注信息条
        fbItemBetIn:cc.Prefab,

        //输出投注信息条
        fbItemBetOut:cc.Prefab,

        //系统消息
        fbSystemInfo:cc.Prefab,

        //时间消息
        fbTime:cc.Prefab,

        //投注详情
        fbBetDetailPop:cc.Prefab,
        fbBetDetail28Pop:cc.Prefab,

        //聊天node
        chatEmotionContent:cc.Node,

        //表情包
        emotionAtlas:cc.SpriteAtlas,
 
        //表情页
        emotionContent:cc.Node,

        //表情节点
        emotionNode:cc.Node,
  
        //表情栏触摸范围外
        ndEmotionTouch:cc.Node,

        betPanelManage:cc.Node,

        //登录界面
        fbloginPop:cc.Prefab,

        _msgLists:[],//聊天消息列表
        _reConect:false,//是否重连
        _isOut:false,//是否自己的消息
        _curMsgHeight:30,//当前聊天信息长度
        _curMsgOff:0,//当前偏移
        _curShowTime:false,//当前显示时间

        isEmotionMoving:false,//表情展开中
        isEmotionOpen:false,//是否打开表情
        isEmotionPanelMoving:false,

        _roomID:"",//房间id
        _roomLotteryCode:"",//房间彩种id
          
        _upTime:0,//聊天信息定时器
        _isAddMsg:true,//是否加入信息
        _showMing:false//是否刷新余额

    },

    onLoad: function () {
        //开奖信息
        this.betContent.getComponent("BetControl").initBetControl(this._roomLotteryCode);

        //余额
        this.labGold.string = User.getBalance().toFixed(2)+'元宝';

        //投注面板初始化
        this.betPanelManage.getComponent(this.betPanelManage.name).init(this._roomLotteryCode,this._roomID);  
      
        //聊天室页面信息初始化
        //聊天室名
        var chatName = LotteryUtils.getLotteryTypeDecByLotteryId(this._roomLotteryCode);
        this.labChatName.string = chatName;
        this._msgLists = [];
        this._reConect = true;
        this._isOut = false;
        this._curMsgHeight = 30;
        this._showMing = false;
        this.curMsgOff = 0; 

        //表情栏
        this.ndEmotionTouch.on(cc.Node.EventType.TOUCH_START, function (event) {
            if(this.ndEmotionTouch.active == false)
                return;
            if(this.isEmotionOpen == true)
            {
                this.emotionPanelEnd();
                return;
            }       
        }.bind(this), this);
        
        this.emotionContent.on(cc.Node.EventType.TOUCH_START, function (event) {
        }.bind(this), this);

        this.emotionContent.on(cc.Node.EventType.TOUCH_MOVE, function (event) {
        }, this);
        
        //表情加载
        for(var i = 0; i<this.emotionAtlas.getSpriteFrames().length; i++){      
            var line_x = i%7;
            var line_y = parseInt(i/7)+1;   
            var emotionSpritFrame = this.emotionAtlas.getSpriteFrames()[i];
            var emotionNode = cc.instantiate(this.emotionNode);
            this.emotionContent.addChild(emotionNode);
            emotionNode.active = true;
            emotionNode.getComponent(cc.Sprite).spriteFrame = emotionSpritFrame;
            emotionNode.x = 150+ emotionNode.x + (line_x-1)*(128+20);
            emotionNode.y = emotionNode.y - (line_y-1)*(128+20);
            emotionNode.name = emotionSpritFrame.name;    
        }

        window.Notification.on("moneyShow",function(data){
            this.moneyShow();
        },this);

        this.initEventHandlers();
        this.node.runAction(cc.sequence(cc.delayTime(0.1), cc.callFunc(function(){//延迟0.1s进行加载
            if(CL.NET.isConnect())
            {
                this.joinChatRoom(1);
            }
                
            this.swChat.node.active = false;
            this.node.runAction(cc.sequence(cc.delayTime(0.5), cc.callFunc(function(){//延迟3s进行加载
                this.swChat.node.active = true;
                this.swChat.node.emit("fade-in"); 
            }.bind(this))));
        }.bind(this))));
    },

    init: function(data){
     //   cc.log('room_chat_pop 房间',data);
        this._roomLotteryCode =data.lottery;  //彩种ID
        this._roomID =data.chatRoomID;
    },

    //用户余额
    moneyShow:function(){
        if(this._showMing)
        {
            return;
        }
        this.labGold.string = '';
        this._showMing = true;
        var recv = function(ret){
            ComponentsUtils.unblock();
            this._showMing = false;
            if(ret.Code === 0)
            {
                User.setBalance(ret.Balance);
                User.setGoldBean(ret.Gold);
             //   cc.log('bet 当前用户余额',User.getBalance());
            }
            else
            {
                ComponentsUtils.showTips(ret.Msg);
            }
            this.labGold.string = User.getBalance().toFixed(2)+'元宝';
        }.bind(this);
        var data = {
            Token:User.getLoginToken(),
            UserCode:User.getUserCode(),
        }
        CL.HTTP.sendRequest(DEFINE.HTTP_MESSAGE.GETUSERMONEY, data, recv.bind(this),"POST"); 
        ComponentsUtils.block();
        
    },

    //删除表情
    onEmotionDelBtn:function(){
        if(this.edMsg.string != "")
        {
           var str1 = this.edMsg.string.charAt(this.edMsg.string.length -1);
           if(str1 == "]")
           {
               var str4 = this.edMsg.string.substring(this.edMsg.string.length -4);
               var index = str4.indexOf("["); 
               if(index != -1)
               {
                    //cc.log("删除表情字符串");
                    var dellen = 4-index;
                    this.edMsg.string = this.edMsg.string.substring(0,this.edMsg.string.length-dellen);
               }
           }
        }
    },

    update: function(dt){
        this._upTime += dt;
        if(this._upTime > 0.1){  
            if(this._isAddMsg)
            {
                this._isAddMsg = false;
                if(this._msgLists.length>0)
                {
                    this.publicMsg( this._msgLists.splice(this._msgLists.length[0],1));
             //       cc.log("chat 删除一条记录："+this._msgLists.length);
                }
                this._isAddMsg = true;
            }
            this._upTime = 0;//每0.1秒重置为0，以达到循环显示  
        }   
    },

    addTimeMsg:function(time){
        var timeTxt = Utils.getYMDHMbyTime(time,"-",":");
      //  cc.log("chat 显示时间："+timeTxt);
        var item = null;
        item = cc.instantiate(this.fbTime);
        item.getComponent('chat_msg_systemTime_item').init(timeTxt); 
        try {
            this.swChat.content.addChild(item);
            this.updateHeight(item.height,20,false);
        } catch (error) {
            //cc.log("chat addSystemMsg Erro:",error);
        }

        this._curShowTime = time;
    },

    addShowTime :function(time,msgtype){
        if(msgtype == 1)//普通聊天信息
        {
            if(Math.abs(this._curShowTime-time)>=300)//间隔大于5分钟显示时间
            {
                 this.addTimeMsg(time);
            }
        }
        else if(msgtype == 2)//投注信息
        {
            if(Math.abs(this._curShowTime-time)>=60)//间隔大于1分钟显示时间
            {
                 this.addTimeMsg(time);
            }
        } 
    },

    //聊天信息重置聊天位置
    updateHeight:function(itemHeight,space,isout){
        this._curMsgHeight = this.swChat.content.height;
        if(this._curMsgHeight >= 1400)
        {
            var offy = this.swChat.getScrollOffset().y; 
            if( this._curMsgOff != 0 &&( offy <= this._curMsgOff-200 || offy >= this._curMsgOff+200)) 
            {
                this._curMsgOff = this.swChat.getScrollOffset().y; 
                if(isout)
                    this.swChat.scrollToBottom(0); 
                return;
            }
            else
            {
                this.swChat.scrollToBottom(0); 
                this._curMsgOff = this.swChat.getScrollOffset().y; 
            } 
        }
    },

    publicMsg:function(msg){
        this._isOut = false;
        if( this.swChat.content.childrenCount>50)
        {
            this.swChat.content.removeChild(this.swChat.content.children[0]);
            this.updateHeight(-(this.swChat.content.children[0].height),-20,this._isOut);
        }
        
        var obj = msg[0].data;
        var curTime = msg[0].time;
        if(obj.MsgType == 2){ //玩家聊天消息
            this.addShowTime(curTime,1);
          
            var msgContent = Utils.getHarmonious(obj.content);

            var item = null;
            var flow = "";
            if(obj.userid != User.getUserCode()){
                flow = "in";
                item = cc.instantiate(this.fbItemIn);
            }else{
                flow = "out";
                this._isOut = true;
                item = cc.instantiate(this.fbItemOut);
            }
            var data0 = {
                head:obj.avatarUrl,
                name:obj.nickName,
                txt:msgContent,
                flow:flow,
            };
            
            item.getComponent('chat_msg_outin_item').init(data0); 
            this.swChat.content.addChild(item);
            this.updateHeight(item.height,20,this._isOut);
        }else if(obj.MsgType == 1){ //系统消息
            var sysObj = obj;
            switch (sysObj.CustomMsgType )
            {
                case DEFINE.RECV_CHAT_MSG_TYPE.CHAT_PUBLIC_MuteList:
                {
                    ComponentsUtils.showTips("xxx被禁言");
                    var rtcontent = "<color=#00F7E8>" + sysObj.Name + "</color>" + "<color=#ffffff>" + sysObj.Content + "</color>";
                    var data0 = {
                        rtContent:rtcontent,
                        type:cc.TextAlignment.CENTER,
                    };
                    this.addSystemMsg(data0);
                }
                break;
                case DEFINE.RECV_CHAT_MSG_TYPE.CHAT_PUBLIC_Bet://投注消息
                {
                    this.addShowTime(curTime,2);
                  //  cc.log("chat RECV BET:" + sysObj.Data.Name,sysObj.Data);
                    var item = null;
                    if(sysObj.Data.Name == User.getNickName())
                    {
                        item = cc.instantiate(this.fbItemBetOut);
                        this._isOut = true;
                    }
                    else
                    {
                        item = cc.instantiate(this.fbItemBetIn);
                    }

                    var data0 = {
                        name:sysObj.Data.Name,
                        money:LotteryUtils.moneytoServer(sysObj.Amount),
                        isuse:sysObj.IsuseName,
                        lotteryName:sysObj.LotteryName,
                        buttype:sysObj.BuyType,
                        head:sysObj.Data.AvatarUrl,
                    };
                    item.getComponent('chat_msg_bet_outin_item').init(data0); 

                    var detailData = {
                        data:sysObj,
                        IsuseName:sysObj.IsuseName,
                        Amount:LotteryUtils.moneytoServer(sysObj.Amount),
                        OrderCode:sysObj.OrderCode,
                        BuyType:sysObj.BuyType
                    };
                    var clickEventHandler = new cc.Component.EventHandler();
                    clickEventHandler.target = this.node; 
                    clickEventHandler.component = "room_chat_pop"
                    clickEventHandler.handler = "onCheckBetCallBack";
                    clickEventHandler.customEventData = detailData;
                    item.getChildByName("spBg").getComponent(cc.Button).clickEvents.push(clickEventHandler);
                    this.swChat.content.addChild(item);    
                    this.updateHeight(item.height,20,this._isOut);
                }
                break;
                case DEFINE.RECV_CHAT_MSG_TYPE.CHAT_PUBLIC_Notice://系统公告
                {
                    var rtcontent = "<color=#ffffff>" + sysObj.Content + "</color>";
                    var data0 = {
                        rtContent:rtcontent,
                        type:cc.TextAlignment.CENTER,
                    };
                 //   cc.log("chat 系统公告 "+rtcontent);
                    this.addSystemMsg(data0);
                }
                break;
                case DEFINE.RECV_CHAT_MSG_TYPE.CHAT_PUBLIC_Award://中奖消息
                {
                    var data0 = {
                        rtContent:sysObj.Content,
                        type:cc.TextAlignment.CENTER,
                    };
                 //   cc.log("chat 系统中奖 "+rtcontent);
                    this.addSystemMsg(data0);
                }
                break;
            } 
        }
        else if(obj.MsgType == 3)//玩家加入
        {
            this.addSystemMsg(obj);
        }
    },

    initEventHandlers:function(){
        window.Notification.on('rjoin_push',function(data){
            CL.NET.roomid = self._roomID;
        }.bind(this));

        window.Notification.on('otherjoin_push',function(data){ //有玩家加入
            var obj  = data;
            if(cc.sys.isNative)
            {
                if(Object.prototype.toString.call(data) !== "object")
                {
                    obj  =  eval('(' + data + ')');
                }
            }
            obj.MsgType = 3;
            var obj0 = new Object();
            obj0.time = 0;
            obj0.data = obj;
            this._msgLists.push(obj0);
        //    cc.log("chat 增加一条记录："+this._msgLists.length);
            //this.addSystemMsg(obj0);
            cc.log("chat join otherjoin_push");
        }.bind(this));

        window.Notification.on('sysmsg_push',function(data){
            cc.log("chat sysmsg_push"); 
            this._msgLists.push(data);
       //     cc.log("chat 增加一条记录："+this._msgLists.length);
            //this.publicMsg(data,true);
        }.bind(this));
        
        window.Notification.on('newmsg_push',function(data){
            cc.log("chat newmsg_push");
            this._msgLists.push(data);
       //     cc.log("chat 增加一条记录："+this._msgLists.length);
            //this.publicMsg(data,false); 
        }.bind(this));

        window.Notification.on('rlogin_push',function(data){
            cc.log("chat rlogin_push");
            if(data)
            {
                this.joinChatRoom(0);
            }
        }.bind(this));
    },

    onCheckBetCallBack:function(event, customEventData){
        var canvas = cc.find("Canvas");
        if(customEventData.data.LotteryName =="幸运28" || customEventData.data.LotteryName =="加拿大28"){
            var chatBetDetailPop = cc.instantiate(this.fbBetDetail28Pop);
            chatBetDetailPop.getComponent('bet_detail28_pop').init(customEventData); 
            canvas.addChild(chatBetDetailPop);    
        }else{
            var chatBetDetailPop = cc.instantiate(this.fbBetDetailPop);
            chatBetDetailPop.getComponent('bet_detail_pop').init(customEventData); 
            canvas.addChild(chatBetDetailPop);
        }
    },

    addSystemMsg:function(data)
    {
        //cc.TextAlignment.LEFT
        //cc.TextAlignment.CENTER
        //cc.TextAlignment.RIGHT
        var item = null;
        item = cc.instantiate(this.fbSystemInfo);
  
        item.getComponent('chat_msg_system_item').init(data); 
        try {
            this.swChat.content.addChild(item);
            this.updateHeight(item.height,20,false);
        } catch (error) {
            //cc.log("chat addSystemMsg Erro:",error);
        }
    },


    //投注
    betBtnCallback:function(event){    
        if(this.isEmotionOpen == true)
        {
            this.emotionPanelEnd();
            return;
        }

        if(User.getIsvermify())
        {
            this.betPanelManage.getComponent(this.betPanelManage.name).onOpenInfo(false);   
        }
        else //前往登录
        {
            var callback = function callback(ret){
                if(ret && ret == true)
                {
                    this.betPanelManage.getComponent(this.betPanelManage.name).onOpenInfo(false); 
                }   
            }.bind(this)
            this.goToLogin(callback);
        }   
    },

    //isshow 1是需要历史请求，0不需要历史请求
    joinChatRoom:function(isshow){
        var rtcontent = "<color=#00F7E8>" + User.getNickName() + "</color>" + "<color=#ffffff>"+ "进入了房间" + "</color>";
        var data = {
            rtContent:rtcontent,
            type:cc.TextAlignment.CENTER,
        };
        
        var json = JSON.stringify(data); 
        CL.NET.joinRoom(this._roomID,json,isshow);
    },

    //发送聊天信息
    onSendMsgBtn:function(event){
        if(!User.getIsvermify())
        {
            //ComponentsUtils.showTips("未登录，不能发送信息！");
            var callback = function callback(ret){
                if(ret && ret == true)
                {
                    this.onSendMsgBtn();
                }   
            }.bind(this)
            this.goToLogin(callback);
            return;
        }

        if(!CL.NET.isConnect())
        {
            cc.log("chat room 房间内断连 ");
            return;
        }

        var editBoxText = this.edMsg.string;
        editBoxText = editBoxText.replace(/^\s+|\s+$/g, '');

        if(editBoxText == ""){
            ComponentsUtils.showTips("不能发送空白信息");
        }else{ 
            var content = new Object(); 
            content.content = editBoxText;
            content.userid = User.getUserCode();
            content.MsgType = 2;
            content.avatarUrl = User.getAvataraddress();
            content.nickName = User.getNickName();
            var json = JSON.stringify(content); 
            this.edMsg.string = "";
            CL.NET.send_group_msg(json);  
            //发送消息后，关闭表情栏
            if(this.isEmotionOpen == true)
            {
                this.emotionPanelEnd();
            }
        }   
    },

    //打开表情栏
    emotionPanelBtnCallBack:function(event){

        if(this.isEmotionOpen == true)
        {
            this.emotionPanelEnd();
            return;
        }
        if(this.isEmotionMoving == false)
        {
            this.ndEmotionTouch.active = true;
            this.chatEmotionContent.runAction(cc.sequence(cc.moveTo(0.2, cc.p(0,this.chatEmotionContent.y+440)), cc.callFunc(function(){
                this.isEmotionMoving = false;
                this.isEmotionOpen = true;
            }.bind(this))));  
            this.isEmotionMoving = true;
        }
    },

    //关闭表情栏
    emotionPanelEnd:function(event){
        if(this.isEmotionMoving == false)
        {
            this.ndEmotionTouch.active = false;
            this.chatEmotionContent.runAction(cc.sequence(cc.moveTo(0.2, cc.p(0,this.chatEmotionContent.y-440)), cc.callFunc(function(){
                this.isEmotionMoving = false;
                this.isEmotionOpen = false;
            }.bind(this))));  
            this.isEmotionMoving = true;
        }
    },

    //当键盘弹出编辑框获得焦点时调用
    onEditDidBegan: function(editbox, customEventData) {

        if(this.isEmotionOpen == true)
        {
            this.emotionPanelEnd();
            return;
        }
    },

    //选择表情
    emotionBtnCallback:function(event){
        var currentTarget = event.getCurrentTarget();
    //    cc.log("emotionBtnCallback:"+currentTarget.name);
        var emotionStr = "["+currentTarget.name+"]";
        if(this.edMsg.string.length+ emotionStr.length>128)
        {
            return;
        }
        this.edMsg.string = this.edMsg.string + emotionStr;
    },

    //其他按钮
    chatOtherBtnCallback:function(event){
        var otherBtnContent = this.node.getChildByName("content").getChildByName("OtherBtnContent");
        
        if(otherBtnContent.active == true){
            otherBtnContent.active = false;
        }else{
            otherBtnContent.active = true;
        }  
    },
    
    //关闭界面
    backBtnCallback:function(event){
        CL.NET.leaveRoom(this._roomID);
      
        window.Notification.offType("newmsg_push");
        window.Notification.offType("sysmsg_push");
        window.Notification.offType("rjoin_push");
        window.Notification.offType("otherjoin_push");
        window.Notification.offType("rlogin_push");
        
        window.Notification.offType("gotoBet");
        window.Notification.offType("moneyShow");

        this._msgLists = [];
     //   cc.log("chat 清理消息记录："+this._msgLists.length);

        this.node.getComponent("Page").backAndRemove();
    },
    
    onClose:function(){
        this.backBtnCallback();
    },

    //前往登录
    goToLogin:function(callback){
        var canvas = cc.find("Canvas");
        var loginPop = cc.instantiate(this.fbloginPop);
        canvas.addChild(loginPop);
        loginPop.getComponent(loginPop.name).setCallBack(callback.bind(this));
    }
    
});

